package com.kimehwa.studyboot.zuoalgs;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Scanner;

/**
 * @author xiaodongguan
 * @description 判断二叉树是否为平衡二叉树
 * @since 2021-07-29 07:46
 */
public class BooleanIsBalanceTree {

//    private static boolean isBalanceTree(int[][] trees) {
//        // 先判断这个树是否存在,好烦 给的树的形状不是一个树，是一个数组
//        if (trees == null || trees[0].length == 0) {
//            return false;
//        }
//        // 要先把数组变为tree吗

//    }

//    // 这里怎么转化
//    private TreeNode reverseTree(int[][] trees){
//        TreeNode root = new TreeNode(trees[0][0]);
//
//    }
    // 这里构造的都不是本树
    @AllArgsConstructor
    private static class TreeNode{
        int vals;
        int left;
        int right;
    }

    static TreeNode[] trees = null;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int root = scanner.nextInt();
        trees = new TreeNode[n+1];
        for (int i = 0; i < n; i++) {
            int val = scanner.nextInt();
            int left = scanner.nextInt();
            int right = scanner.nextInt();
            trees[n] = new TreeNode(val,left,right);
        }
        System.out.println(isBalance(root).isBalance);
    }
    // 给了一个结构 returnWal
    public static class ReturnVal{
        public boolean isBalance;
        public int height;
        ReturnVal(boolean isBalance,int height){
            this.isBalance = isBalance;
            this.height = height;
        }
    }
    // 这个思想
    public static ReturnVal isBalance(int index){
        if(index == 0){
            return new ReturnVal(true,0);
        }
        ReturnVal left = isBalance(trees[index].left);
        if(!left.isBalance) return new ReturnVal(false,0);
        ReturnVal right = isBalance(trees[index].right);
        if(!right.isBalance) return new ReturnVal(false,0);
        int height = Math.max(left.height, right.height)+1;
        boolean isBalance = Math.abs(left.height-right.height)<=1&&left.isBalance&&right.isBalance;
        return new ReturnVal(isBalance,height);

    }


















}
